//获取当前用户信息
UserInfo = {
    init: function (onComplete) {
        var User;
        var sysUser = null;
        var me = this;

        $.ajax({
            url: '/sys-user/get',
            type: 'post',
            async: false,
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            success: function (data) {
                User = data;
                if (User.code === 0) {
                    sysUser = User.sysUser;
                    me.userId = sysUser.id;
                    me.userName = sysUser.userName;
                    me.postList = User.postList;
                    window.top.UserInfo = me;
                } else {
                    onComplete();
                }
            }.bind(this)
        });
    },
    userId: null,//用户ID
    userName: null,//用户名称
    postList: null
};

//获取Url参数
RequestURLParam = {
    getParam: function (name) {
        var lurl = window.location.href;
        if (lurl.indexOf(name) < 0) return;
        if (lurl.indexOf("?") < 0) {
            return "";
        } else {
            var value;
            var str = location.href; //取得整个地址栏
            var num = str.indexOf("?")
            str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]
            var arr = str.split("&"); //各个参数放到数组里
            for (var i = 0; i < arr.length; i++) {
                num = arr[i].indexOf("=");
                if (num > 0 && arr[i].substring(0, num) == name) {
                    return value = arr[i].substr(num + 1);
                }
            }
            return "";
        }
    }
}

/**
 * 提交Action请求
 * 参数url请求action;dataPrms参数;callback回调函数,post提交方式post或者get,ayn异步设置,objControl对象控制为true时 action处理完之前对象不可用，showTilte显示标题信息，showMask显示内容
 */
function ActHttpRequest(url, dataPrms, callback, post, ayn, objControl, showTilte, showMask) {
    var operatTxt = "加载中";
    if (showTilte && showTilte.length > 0) {
        operatTxt = showTilte;
    }
    var postTxt = "post";
    if (post) {
        postTxt = post;
    }
    var aynTxt = false;
    if (ayn) {
        aynTxt = true;
    }
    $.ajax({
        async: aynTxt,
        type: postTxt,
        dataType: "json",
        url: url,
        data: dataPrms,
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        timeout: 60000,//超时时间设置为1分钟；
        success: function (data, textStatus) {
            callback(data);
        },
        complete: function (XMLHttpRequest, textStatus) {
            if (objControl && objControl.attr) {
                objControl.attr("disabled", false);
            }
        },
        error: function (a, b, c) {
            // 请求出错处理,依然初始化咨询节点信息
            if (b == 'timeout') {
                layer.alert("请求超时，请再次尝试！");
            } else {
                layer.alert(url + "请求异常");
            }
        }
    });
}

Tree = {
    getTree: function (treeObj, url, id, pid, callBack) {
        ActHttpRequest(url, {}, function (data) {
            if (data.code && data.code != '200') {
                mini.alert(data.message);
                return;
            }
            treeObj.loadList(data.List, id, pid);
            if (callBack) {
                eval(callBack + "()");
            }
        }, null, null, null, null, true);
    },
    addTreeRoot: function (url, data, treeObj, callBack) {
        ActHttpRequest(url, data, function (data) {
            if (data.OK == "OK") {
                if (callBack) {
                    eval(callBack + "()");
                }
            } else {
                mini.alert(data.message);
            }
        }, null, null, null, '新增中。。。', true);
    },
    addTreeCurrent: function (url, data, treeObj, callBack) {
        ActHttpRequest(url, data, function (data) {
            if (data.OK == "OK") {
                if (callBack) {
                    eval(callBack + "()");
                }
            } else {
                mini.alert(data.message);
            }
        }, null, null, null, '新增中。。。', true);
    },
    addTreesub: function (url, data, treeObj, callBack) {
        ActHttpRequest(url, data, function (data) {
            if (data.OK == "OK") {
                if (callBack) {
                    eval(callBack + "()");
                }
            } else {
                mini.alert(data.message);
            }
        }, null, null, null, '新增中。。。', true);
    }
}

windowtab = {
    TABBID: "#contenttabs",
    /**
     * 通过tab打开窗口
     * @param {Object} title tab标题
     * @param {Object} href  打开的url地址
     * @return {TypeName}
     */
    addTab: function (title, href, key) {
        var id = UUID.prototype.createUUID();
        var tabs = mini.get(this.TABBID);
        var id = "tab$" + id;
        var name = title;
        if (key) {
            name = key;
        }
        var tab = tabs.getTab(name);
        if (!tab) {
            tab = {};
            tab._nodeid = id;
            tab.name = name;
            tab.title = title;
            tab.showCloseButton = true;
            //这里拼接了url，实际项目，应该从后台直接获得完整的url地址
            tab.url = href;
            tabs.addTab(tab);
        }
        tabs.activeTab(tab);
    },
    /**
     * 回调指定tab内的方法
     * @param {Object} id tab的id
     * @param {Object} objfun 回调函数
     * @param {Object} obprams 函数参数 json对象
     */
    execCallBackFun: function (id, objfun, obprams) {
        var tabs = mini.get(this.TABBID);
        var tab = tabs.getTab(id);
        var obj = tabs.getTabIFrameEl(tab).contentWindow;
        if (obprams) {
            obj.eval(objfun + "(" + obprams + ")");

        } else {
            obj.eval(objfun + "()");
        }
    },
    /**
     * 获取当前选择的tab的ID
     * @return {TypeName}
     */
    getCurrentSelectTabID: function () {
        var tabs = mini.get(this.TABBID);
        var currenttab = tabs.getActiveTab();
        if (currenttab) {
            return currenttab.name;
        } else {
            return null;
        }
    },
    /**
     * 根据TabID关闭指定Tab
     * @param {Object} tab的ID
     * @return {TypeName}
     */
    CloseTab: function (id) {
        if (id && id.length > 2) {

        } else {
            id = this.getCurrentSelectTabID();
        }
        var tabs = mini.get(this.TABBID);
        tabs.removeTab(id);
    },
    /**
     * 根据TabID关闭指定Tab
     * @param {Object} tab的ID
     * @return {TypeName}
     */
    CloseAllTab: function () {
        var newtabs = [];
        var tabs = mini.get(this.TABBID);
        tabs.removeAll('');
    },
    /**
     * 刷新tab
     * @cfg
     *example: {tabTitle:'tabTitle',url:'refreshUrl'}
     *如果tabTitle为空，则默认刷新当前选中的tab
     *如果url为空，则默认以原来的url进行reload
     */
    refreshTab: function (cfg) {
    }
}

//open 1为直接打开 0为下载
function getfile(fileId, open) {
    var url = "";
    ActHttpRequest("download/getdocServer.do", "", function (data) {
        console.log(data)
        if (data.OK == 'OK') {
            docServer = data.docServer;
            url = docServer + "/downloadfile?isopen=" + open + "&fileId=" + fileId;
        } else {
            url = "download/downloadfile.do?isopen=" + open + "&fileId=" + fileId;
            console.log(url)
        }
    }, null, null, null, null, false);
    if (open == 0) {
        window.open(url)
    }
    return url;
}

//获取图片
function getImage(type) {
    var url = "";
    ActHttpRequest("sysImgconfig/list.do?sysImgconfig.imgType=" + type, "", function (data) {
        if (data.OK == 'OK' && data.List.length > 0) {
            url = getfile(data.List[0].attachId, 1);
        }
        sysImgconfig
    }, null, null, null, null, false);
    return url;
}


//获取图片
function deletefile(fileID) {
    ActHttpRequest("deleteFile/deletefile.do?fileId=" + fileID, "", function (data) {
        if (data.OK == 'OK') {
            return true;
        } else {
            mini.alert(data.message)
        }
    }, null, null, null, null, false);
}

function getTreeSelect(Obj, url, data, id, pid, callBack) {
    ActHttpRequest(url, data, function (data) {
        if (data.statusCode && data.statusCode != '200') {
            mini.alert(data.message);
            return;
        }
        if (Obj !== undefined && Obj)
            Obj.loadList(data.List, id, pid);
    }, null, null, null, null, true);
}

function getSelectOption(Obj, url, data, value, callBack) {
    ActHttpRequest(url, data, function (data) {
        if (data.statusCode && data.statusCode != '200') {
            mini.alert(data.message);
            return;
        }
        if (Obj !== undefined && Obj)
            Obj.setData(data.List);
        if (value) {
            Obj.setValue(value);
        }
        if (typeof callBack == "function")
            callBack(data);
    }, null, null, null, null, true);
}

function selectForm(onSelected, rootPath) {
    if (rootPath == null || rootPath == '')
        rootPath = '/';
    if (rootPath.substring(rootPath.length - 1, rootPath.length) != '/')
        rootPath += '/';
    var url = rootPath + 'base/form/formSelector.html';
    mini.open({
        url: url,
        title: '选择表单', width: 600, height: 500,
        onload: function () {
            //给对话框传参数！
            //var iframe = this.getIFrameEl();
            //iframe.contentWindow.SetData("");
        },
        ondestroy: function (e) {
            if (e == "close") {
                return;
            }
            if (typeof onSelected == "function")
                onSelected(e);
        }
    });
}

function AttachUpload() {
    this.uploader = "",
        this.accept = null,
        this.init = function (divID, uploadUrl, billID, billName, Path, callback, limit, autoupload) {
            Path = encodeURI(Path);
            var server = "uploadFile/upload.do";
            var fileNumLimit = 5;
            var auto = true;
            if (uploadUrl) {
                server = uploadUrl;
            }
            if (limit) {
                fileNumLimit = limit;
            }
            if (autoupload == false) {
                auto = false;
            }
            // 初始化Web Uploader
            this.uploader = WebUploader.create({
                auto: auto,// 选完文件后，是否自动上传。
                swf: '/common/webuploader/Uploader.swf',// swf文件路径
                server: server,// 文件接收服务端。
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: '#' + divID,
                chunked: true,  //分片处理
                chunkSize: 20 * 1024 * 1024, //每片20M
                threads: 1,//上传并发数。允许同时最大上传进程数。
                formData: {"BillId": billID, "Path": Path},
                fileNumLimit: fileNumLimit//上传的文件总数
            });
            this.uploader.on('uploadSuccess', function (file, data) {
                if (data.OK == "OK") {
                    $('#' + billName).val(data.fileID);
                    if (callback) {
                        if (typeof callback == 'string') {
                            eval(callback + "('" + data.fileID + "')");
                        } else if (typeof callback == 'function') {
                            callback(file, data);
                        }
                    }
                } else {
                    mini.alert(data.message);
                }
            });

            this.uploader.on('uploadError', function (file) {
                $('#' + file.id).find('p.state').text('上传出错');
            });

            this.uploader.on('uploadFinished', function () {
            });
        },
        this.reset = function () {
            this.uploader.reset();
        }
}

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
};

String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};

/**
 * 加法运算，避免数据相加小数点后产生多位数和计算精度损失。
 *
 * @param num1加数1 | num2加数2
 */
function numAdd(num1, num2) {
    var baseNum, baseNum1, baseNum2;
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    return (num1 * baseNum + num2 * baseNum) / baseNum;
};

/**
 * 减法运算，避免数据相减小数点后产生多位数和计算精度损失。
 *
 * @param num1被减数 | num2减数
 */
function numSub(num1, num2) {
    var baseNum, baseNum1, baseNum2;
    var precision;// 精度
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
    return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
}

/**
 * 乘法运算，避免数据相乘小数点后产生多位数和计算精度损失。
 *
 * @param num1被乘数 | num2乘数
 */
function numMulti(num1, num2) {
    var baseNum = 0;
    try {
        baseNum += num1.toString().split(".")[1].length;
    } catch (e) {
    }
    try {
        baseNum += num2.toString().split(".")[1].length;
    } catch (e) {
    }
    return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
}

/**
 * 除法运算，避免数据相除小数点后产生多位数和计算精度损失。
 *
 * @param num1被除数 | num2除数
 */
function numDiv(num1, num2) {
    var baseNum1 = 0, baseNum2 = 0;
    var baseNum3, baseNum4;
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    with (Math) {
        baseNum3 = Number(num1.toString().replace(".", ""));
        baseNum4 = Number(num2.toString().replace(".", ""));
        return (baseNum3 / baseNum4) * pow(10, baseNum2 - baseNum1);
    }
};

//时间h:mm加法
function timehmmadd(begin, Lengthtime) {
    var beginh = begin.substring(0, begin.indexOf(':'));
    var beginm = begin.substring(begin.indexOf(':') + 1);

    var Lengthtimeh = Lengthtime.substring(0, Lengthtime.indexOf(':'));
    var Lengthtimem = Lengthtime.substring(Lengthtime.indexOf(':') + 1);

    var endTimeh = numAdd(beginh, Lengthtimeh);
    var endTimem = numAdd(beginm, Lengthtimem);

    if (endTimeh > 23) {
        endTimeh = endTimeh - 24;
    }
    if (endTimem > 59) {
        endTimem = endTimem - 60;
        endTimeh++;
    }
    if (endTimem < 10) {
        endTimem = '0' + endTimem
    }
    return endTimeh + ':' + endTimem
}
